package com.wsdcd.zlg.sb.model.service.impl;

import com.wsdcd.zlg.sb.core.exception.ERPException;
import com.wsdcd.zlg.sb.mapper.ProductMapper;
import com.wsdcd.zlg.sb.model.entity.Product;
import com.wsdcd.zlg.sb.model.service.ProductService;
import com.wsdcd.zlg.sb.util.PageParameter;
import com.wsdcd.zlg.sb.util.PagerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@AllArgsConstructor
@Service
public class ProductServiceImpl implements ProductService {
	private final ProductMapper productMapper;

	@Override
	public PagerUtil<Product> selectByPage(PageParameter pageParameter) {
		int count = productMapper.getCount();
		List<Product> data = productMapper.selectByPage(pageParameter);
		return new PagerUtil<>(count, data);
	}

	@Override
	public void insert(Product product) throws ERPException {
		String productName = product.getProductName();
		if(productName == null || productName.trim().equals("")){
			throw new ERPException("输入的产品名称不能为空");
		}
		Product oldProduct = productMapper.selectByProductName(productName);
		if(oldProduct!=null){
			throw new ERPException("输入的产品名称已被占用");
		}
		String productType = product.getProductType();
		if(productType == null || productType.trim().equals("")){
			throw new ERPException("输入的产品类型不能为空");
		}
		productMapper.insert(product);
	}

	@Override
	public Product selectByProductId(String productId) {
		return productMapper.selectByProductId(productId);
	}

	@Override
	public void update(Product product) throws ERPException{
		int productId = product.getProductId();
		String productIdString = productId+"";
		Product oldProduct = productMapper.selectByProductId(productIdString);
		if(oldProduct==null){
			throw new ERPException("修改失败，想要修改的产品编号不存在");
		}else if(oldProduct.equals(product)){
			throw new ERPException("修改失败，修改后的数据不能和之前相同");
		}
		String productName = product.getProductName();
		if( productName == null || productName.trim().equals("")){
			throw new ERPException("修改失败，修改后的产品名称不能为空");
		}
		String productType = product.getProductType();
		if( productType == null || productType.trim().equals("")){
			throw new ERPException("修改失败，修改后的产品类型不能为空");
		}
		Product oldProduct2 = productMapper.selectByProductName(product.getProductName());
		if( oldProduct2 != null && oldProduct2.getProductId()!=productId ){
			throw new ERPException("修改失败，想要修改的客户全称已被占用");
		}
		productMapper.update(product);
	}

	@Override
	public void deleteAll(int[] productId) {
		productMapper.deleteAll(productId);
	}

}
